<?php
/**
 * @Name: SettingsLogic.php
 * @Author: yashuai 1762910894@qq.com
 */

namespace App\Http\Logic;

use App\Http\Model\SettingsModel;

class SettingsLogic extends BaseLogic
{

    const WECHAT_TICKET = 'WechatTicket';
    const WECHAT_TOKEN = 'WechatToken';

    const SETTING_NAMES = [
        self::WECHAT_TICKET => '微信JSSDK的Ticket',
        self::WECHAT_TOKEN  => '微信的AccessToken',
    ];

    const SETTING_KEYS = [
        self::WECHAT_TICKET => [],
        self::WECHAT_TOKEN  => [],
    ];

    /**
     * @Desc 设置配置
     * @param array $params
     * @return bool
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model
     * @throws \App\Exceptions\ApiException
     * @author yashuai 1762910894@qq.com
     */
    public function setConfigure(array $params)
    {
        if (!in_array($params['key'], array_keys(self::SETTING_NAMES))) {
            _throw(106002, '配置参数异常');
        }
        $data = array_merge(self::SETTING_KEYS[$params['key']], $params['value']);
        $data = [
            'Desc'  => self::SETTING_NAMES[$params['key']],
            'Value' => json_encode($data)
        ];
        SettingsModel::query()->updateOrInsert(['Key' => $params['key']], $data);
        return true;
    }

    /**
     * @Desc 获取配置
     * @param string $key
     * @return array
     * @author yashuai 1762910894@qq.com
     */
    public function getConfigure(string $key = '')
    {
        if (empty($key)) {
            $config = SettingsModel::query()->get()->toArray();
            $config = _object_to_arr($config);
            $config = array_column($config, null, 'Key');
            $result = [];
            foreach (self::SETTING_NAMES as $key => $desc) {
                $result[$key] = _array_field($config, $key) ?
                    json_decode($config[$key]['Value'], true) :
                    self::SETTING_KEYS[$key];
            }
            return $result;
        } else {
            if (!in_array($key, array_keys(self::SETTING_NAMES))) {
                return [];
            }
            $result = SettingsModel::query()->where('Key', $key)->first();
            if (!empty($result)) {
                $result = $result->toArray();
                $result = json_decode($result['Value'], true);
                return array_merge(self::SETTING_KEYS[$key], $result);
            }
            return self::SETTING_KEYS[$key];
        }
    }

}
